﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using Sustainalytics.ESGRatings.Computing.Service.Exceptions;
using Sustainalytics.ESGRatings.Computing.Service.Extensions;
using Sustainalytics.ESGRatings.BusinessLogic.Computing;
using Sustainalytics.ESGRatings.DataContract;
using Sustainalytics.ESGRatings.DataContract.Mappers;

namespace Sustainalytics.ESGRatings.Computing.Service.Controllers
{
    [RoutePrefix("api/v1/dataprovisioning/governancesets")]
    public class GovernanceDataContainerController : ApiController
    {
        private readonly ComputationEngine _engine;

        public GovernanceDataContainerController(ComputationEngine engine)
        {
            _engine = engine;
        }

        [Route]
        public HttpResponseMessage Delete(Guid? setId)
        {
            if (setId.HasValue)
            {
                _engine.DeleteSet(setId.Value);
            }
            else
            {
                _engine.DeleteGovernanceSets();
            }

            return Request.CreateResponse(HttpStatusCode.NoContent);
        }

        [Route]
        public HttpResponseMessage Get(Guid? setId = null)
        {
            var data = _engine.ReadSets(setId);

            return Request.CreateResponse(HttpStatusCode.OK, data.Select(x => x.Item1));
        }

        [Route]
        public HttpResponseMessage Post(GovernanceDataContainer data)
        {
            ICollection<string> messages;
            if (data.Validate(out messages))
            {
                throw new InvalidInput(messages.Aggregate((i, j) => i + " " + j));
            }

            var id = this._engine.AddGovernanceSet(
                data.SetId,
                data.Companies.ToDomainModel(),
                data.IndicatorTemplates,
                data.CompaniesRawScores,
                data.WeightMatrix,
                data.Modifiers);

            return Request.CreateResponse(HttpStatusCode.Created, id);
        }
    }
}